// +----------------------------------------------------------------------
// | JavaWeb_Cloud_Pro微服务旗舰版框架 [ JavaWeb ]
// +----------------------------------------------------------------------
// | 版权所有 2019~2020 南京JavaWeb研发中心
// +----------------------------------------------------------------------
// | 官方网站: http://www.javaweb.vip/
// +----------------------------------------------------------------------
// | 作者: 鲲鹏 <1175401194@qq.com>
// +----------------------------------------------------------------------

package com.javaweb.auth.exception;

import com.alibaba.fastjson.JSONObject;
import com.javaweb.common.framework.utils.JsonResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator implements WebResponseExceptionTranslator<OAuth2Exception> {

    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) throws Exception {
        ResponseEntity<OAuth2Exception> responseEntity = null;
        try {
            responseEntity = super.translate(e);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        JsonResult jsonResult = new JsonResult();
        OAuth2Exception body = responseEntity.getBody();
        if (e instanceof InvalidGrantException) {
            return new ResponseEntity(jsonResult.error(402, "用户名或密码不正确"), HttpStatus.OK);
        } else if (e instanceof InvalidTokenException) {
            return new ResponseEntity(jsonResult.error(401, "token已失效"), HttpStatus.OK);
        } else {
            return new ResponseEntity(jsonResult.error(401, body.getLocalizedMessage()), HttpStatus.OK);
        }

    }
}
